package com.wangzhixuan.service;

import com.wangzhixuan.db.bean.*;
import com.wangzhixuan.db.dao.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private PaymentDao paymentDao;
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private DoctorService doctorService;

    public long addOrder(Order order){
        Product product= productDao.getProductsByDoctorAndType(order.getDoctorId(), order.getProductTypeId());
        order.setPrice(product.getPrice());
        order.setType(0);
        return orderDao.addOrder(order);
    }
    public long addSpecialOrder(Order order){
        order.setPrice(50d);
        order.setType(1);
        return orderDao.addOrder(order);
    }
    public int updateOrderStatus(long orderId, int status){
        return orderDao.updateOrderStatus(orderId, status);
    }
    
    public Order getOrderById(long orderId) {
        Order order = orderDao.getOrderById(orderId);
        return order;
    }

    public Order getOrderDetail(long orderId) {
        Order order = orderDao.getOrderById(orderId);
        if(order.getType()==0){
            Doctor doctor=doctorService.getDoctorById(order.getDoctorId());
            order.setDoctor(doctor);
            Product product=productDao.getProductsByDoctorAndType(order.getDoctorId(),order.getProductTypeId());
            order.setProduct(product);
        }else{
            JSONObject memoObj=JSONObject.fromObject(order.getMemo());
            order.setMemoObj(memoObj);
        }
        List<Payment> payments=paymentDao.getPaymentsByOrder(orderId);
        order.setPayments(payments);
        List<Comment> comments=commentDao.getCommentsByOrder(orderId);
        order.setComments(comments);
        return order;
    }

    public List<Order> getOrdersByCustomer(long customerId) {
        List<Order> orders = orderDao.getOrdersByCustomer(customerId);
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            if(order.getType()==0){
                Long doctorId=order.getDoctorId();
                if(doctorId!=null&&doctorId>0){
                    Doctor doctor=doctorService.getDoctorDetail(doctorId);
                    order.setDoctor(doctor);
                }
            }else{
                JSONObject memoObj=JSONObject.fromObject(order.getMemo());
                order.setMemoObj(memoObj);
            }
        }
        return orders;
    }

    public long addPayment(Payment payment){
        return paymentDao.addPayment(payment);
    }

}
